# _*_ coding: utf-8 _*_
from odoo import models, fields, api


class ChangeRawProduct(models.TransientModel):
    _name = "change.raw.product"

    def _default_allowed_substitution(self):
        Subt = self.env["bom.product.substitution"]
        move = self.env["stock.move"].browse(self.env.context.get("active_id"))
        if move.bom_line_id:
            return Subt.search([("bom_line_id", "=", move.bom_line_id.id)])

    def _get_move_id(self):
        return self.env["stock.move"].browse(self.env.context.get("active_id"))

    def _get_bom_line_id(self):
        return self._get_move_id().bom_line_id

    def _default_origin_product(self):
        return self._get_move_id().product_id

    def _default_bom_line_product_id(self):
        return self._get_bom_line_id().product_id

    def _default_bom_line_product_qty(self):
        return self._get_bom_line_id().product_qty

    allowed_substitution_ids = fields.Many2many("bom.product.substitution", readonly=True,
                                                default=_default_allowed_substitution)
    substitution_id = fields.Many2one(
        "bom.product.substitution",
        string="Product Substitution",
        domain="[('id','in',allowed_substitution_ids and allowed_substitution_ids[0][2] or [])]",
        required=True
    )
    origin_product_id = fields.Many2one("product.product", string="Origin Product",
                                        default=_default_origin_product, readonly=True)
    bom_line_product_id = fields.Many2one("product.product", string="Bom Line Product",
                                          default=_default_bom_line_product_id, readonly=True)
    bom_line_product_qty = fields.Float(string="Bom Line Product Quantity",
                                        default=_default_bom_line_product_qty, readonly=True)

    def action_change_raw_product_fom_prod(self):
        self.ensure_one()
        move_id = self._get_move_id()
        move_id.active_move_lot_ids = False
        move_id.product_id = self.substitution_id.subt_product_id
        move_id.product_uom_qty = move_id.origin_raw_qty * self.substitution_id.subt_product_qty / self.bom_line_product_qty
